package ua.vn.ticket_scanner.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import ua.vn.ticket_scanner.R;
import ua.vn.ticket_scanner.ui.activity.MainActivity;
import ua.vn.ticket_scanner.network.data.ConnectResult;
import ua.vn.ticket_scanner.network.data.JSONKeys;
import ua.vn.ticket_scanner.network.task.http.CheckTicketTask;
import ua.vn.ticket_scanner.network.utils.ResultRunnable;
import ua.vn.ticket_scanner.nfc.NFCDevice;
import ua.vn.ticket_scanner.nfc.NFCEventHelper;
import ua.vn.ticket_scanner.nfc.ticket.MifareClassicTicket;
import ua.vn.ticket_scanner.nfc.utils.Converter;
import ua.vn.ticket_scanner.utils.VibratorHelper;

/**
 * Created by Ivan on 13.06.13.
 */
public class TicketActivity extends Activity {

    private static final String TAG = "TicketActivity";
    private ProgressBar progressBar;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ticket_layout);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        resolveIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        resolveIntent(intent);
    }

    @Override
    public void onBackPressed() {
        // super.onBackPressed();
        startActivity(new Intent(this, MainActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        progressBar = null;
    }

    private void resolveIntent(Intent intent) {
        String result;
        if (NFCEventHelper.isIntentNFC(intent)) {
            if (NFCEventHelper.isIntentMifareClassic(intent)) {

                MifareClassicTicket ticket = new MifareClassicTicket(intent);

                long id = Converter.toDec(ticket.getId());
                //ticket.writeBlock(1, "BAIZOR 123 123:)");
                String blockData = Converter.toString(ticket.readBlock(1));

                if (blockData == null) {
                    // TODO: NEED TO REPEAT
                }

                result = "ID: " + id + "\n" + "Data: " + blockData;

                animShowTicket();
                checkTicket("" + id);

            } else {
                // TODO: IT'S NOT A TICKET!!!
                animShowWrongTicket();

                NFCDevice nfcDevice = new NFCDevice(intent);
                String fullInfo = nfcDevice.getFullInfo();

                result = "" + fullInfo;
            }
        } else {
            // TODO: ERROR!!!
            result = getResources().getString(R.string.message_unknown_device);
            animShowOtherProblem(result);
        }

        animShowOtherInfo(result);
    }

    private void checkTicket(String ticketCode) {
        CheckTicketTask ticketTask = new CheckTicketTask(ticketCode);
        load(true);
        ticketTask.setOnPostExecute(new ResultRunnable() {
            @Override
            public void run() {
                if (progressBar != null) {
                    load(false);
                    checkResult(mConnectResult);
                }
            }
        });
        ticketTask.execute();
    }

    private void checkResult(ConnectResult connectResult) {
        Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        // Vibrate for 300 milliseconds
        mVibrator.vibrate(300);
        if (connectResult == null) {
            animShowOtherProblem(getResources().getString(R.string.message_connect_failed));
            Log.e(TAG, "Connection result is null!!!");
            VibratorHelper.longVibro();
            return;
        }
        String status = connectResult.get(JSONKeys.STATUS);
        if (status == null || !"valid".equals(status)) {
            String error_code = connectResult.get(JSONKeys.ERROR_CODE);

            if (error_code != null && !error_code.isEmpty()) {
                if ("1".equals(error_code)) {
                    animShowBadRequest(ConnectResult.errorCodes.get(error_code));
                } else if ("2".equals(error_code)) {
                    animShowBadRequest(ConnectResult.errorCodes.get(error_code));
                } else if ("10".equals(error_code)){
                    animShowBadRequest(ConnectResult.errorCodes.get(error_code));
                } else if ("11".equals(error_code)){
                    animShowBadRequest(ConnectResult.errorCodes.get(error_code));
                } else {
                    animShowTicketProblem(ConnectResult.errorCodes.get(error_code));
                }

                VibratorHelper.shortVibro();
            }
        } else {
            animShowGoodTicket();
            VibratorHelper.doubleShortVibro();
        }
    }

    private void load(boolean isLoad) {
        progressBar.setVisibility(isLoad ? View.VISIBLE : View.INVISIBLE);
    }

    private Animation getShowAnimation(boolean isError) {
        if(isError) {
            return AnimationUtils.loadAnimation(this, R.anim.effect_show_right);
        } else {
            return AnimationUtils.loadAnimation(this, R.anim.effect_show_left);
        }
    }

    private void animShowTicket() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.ticketDetected);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(false));
    }

    private void animShowBadRequest(String message) {
        VibratorHelper.longVibro();
        LinearLayout layout = (LinearLayout) findViewById(R.id.requestProblem);
        TextView text = (TextView) findViewById(R.id.badRequestText);
        text.setText(message);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(true));
    }

    private void animShowWrongTicket() {
        VibratorHelper.doubleShortVibro();
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.wrongTicket);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(true));
    }

    private void animShowOtherProblem(String message) {
        VibratorHelper.doubleShortVibro();
        LinearLayout layout = (LinearLayout) findViewById(R.id.otherError);
        TextView text = (TextView) findViewById(R.id.otherErrorText);
        text.setText(message);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(true));
    }

    private void animShowGoodTicket() {
        VibratorHelper.shortVibro();
        LinearLayout layout = (LinearLayout) findViewById(R.id.goodTicket);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(false));
    }

    private void animShowTicketProblem(String message) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.ticketProblem);
        TextView text = (TextView) findViewById(R.id.ticketProblemText);
        text.setText(message);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(getShowAnimation(true));
    }

    private void animShowOtherInfo(String message) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.otherInfo);
        TextView text = (TextView) findViewById(R.id.otherInfoText);
        text.setText(message);
        layout.setVisibility(View.VISIBLE);
        layout.startAnimation(AnimationUtils.loadAnimation(this, R.anim.effect_show_down));
    }
}